package com.mobile.business.grid;

import java.util.HashSet;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.mobile.business.BaseBusiness;
import com.mobile.dao.HibernateSessionFactory;
import com.mobile.model.GridColumn;
import com.mobile.model.GridTable;
import com.mobile.tools.CopyFile;
import com.mobile.tools.FieldInfo;
import com.mobile.tools.HibernateEntityManager;
import com.mobile.tools.HibernateMappingManager;
import com.mobile.tools.cfg.HbmXMLManageUtil;
import com.mobile.tools.cfg.HibernateConfigManagerUtil;
import com.mobile.tools.cfg.SessionFactoryUtil;
import com.mobile.tools.exception.FileIsExistsException;
import com.mobile.tools.exception.FilePathException;

public class GridTableBusinessImpl extends BaseBusiness implements IGridTableBusiness{
	
	private SessionFactoryUtil sessionFactoryUtil ;
	
	
	public SessionFactoryUtil getSessionFactoryUtil() {
		return sessionFactoryUtil;
	}

	public void setSessionFactoryUtil(SessionFactoryUtil sessionFactoryUtil) {
		this.sessionFactoryUtil = sessionFactoryUtil;
	}

	public void save(){
		Session session=HibernateSessionFactory.getSession();
		Transaction transaction=null;
		try {
			transaction=session.getTransaction();
			transaction.begin();
			GridTable gt=new GridTable();
			gt.setDeleteUrl("../hf/sortManager.do?action=ajaxDelete");
			gt.setEditUrl("../hf/sortManager.do?action=ajaxEdit");
			gt.setFormSaveUrl("../hf/sortManager.do?action=ajaxSave");
			gt.setListUrl("../hf/sortManager.do?action=ajaxList");
			//添加栏位信息
			gt.getGridColumns().add(new GridColumn(
					"分类名称",gt,"string",true,"sortName",1,false,null,"类型名称",
					"80%","textfield",true
					));
			gt.getGridColumns().add(new GridColumn(
					"分类类型",gt,"string",true,"sortType",2,false,null,"分类类型",
					"80%","textfield",true
				));
			gt.getGridColumns().add(new GridColumn(
					"创建时间",gt,"string",true,"createDate",3,false,null,"创建时间",
					"80%","textfield",false					
				));
			gt.getGridColumns().add(new GridColumn(
					"排列序号",gt,"string",true,"orderNo",4,false,null,"排列序号",
					"80%","numberfield",true					
				));
			gt.getGridColumns().add(new GridColumn(				
					"收入/支出",
					gt,
					"boolean",
					true,
					"支出",
					"收入",
					"inOrOut",
					5,
					false,
					"收入/支出",
					"80%",
					"radio",
					true,
					"[{boxLabel:\"支出\",value:1},{boxLabel:\"收入\",value:0}]"			
				));
			//添加表单
			//gt.getGridFields().add(new GridField("uniqueCode",""));
			session.save(gt);
			transaction.commit();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			HibernateSessionFactory.rollback(transaction);
			throw new RuntimeException();
		} catch(Exception e){
			e.printStackTrace();
			HibernateSessionFactory.rollback(transaction);
			throw new RuntimeException();
		} finally{
			HibernateSessionFactory.closeSession();
		}
	}
	
	public GridTable getGridTable(String uniqueCode){
		return (GridTable)baseDAO.findById(GridTable.class,uniqueCode);
	}
	/**
	 * 把界面里添加的字段添加hdm.xml文家和修改hibernate 配置文件，并添加<br>
	 * 相应的表以及字段
	 */
	public void createTableXML()
				throws FilePathException,FileIsExistsException{
		
		String gridTableId="10066";
		String sourceEntityName="TEMPLATE_TABLE_01";
		String sourceHbmName="TemplateTable01.hbm.xml";
		String newHbmName="TemplateTable02.hbm.xml";
		String newEntityName="TEMPLATE_TABLE_02";
		String configName="hibernate.cfg.xml";
		String entityClassFilePath="";
		//实体类的文件夹路径
		String entityClassDirPath="";
		
		String sourceHbmFilePath="";
		String newHbmFilePath="";
		String hbmAbsolutePath="";
		
		GridTable gt=this.getGridTable(gridTableId);
		Set<GridColumn> set=gt.getGridColumns();
		
		Set<FieldInfo>  fieldInfoSet=new HashSet<FieldInfo>();
		//初始化fieldInfoSet
		for(GridColumn gc:set){
			FieldInfo fi=new FieldInfo();
			fi.setFieldName(gc.getDataIndex());
			fi.setFieldTypeName(gc.getType());
			fieldInfoSet.add(fi);
		}
		
		Class clazz=this.sessionFactoryUtil
				.getClassMapping(sourceEntityName)
				.getMappedClass() ;
		String className=this.sessionFactoryUtil
						.getClassMapping(sourceEntityName) 
						.getClassName();
		className = className.substring(className.lastIndexOf(".")+1).concat(".class");
		
		entityClassFilePath=clazz
						.getResource(className).getPath();
		
		entityClassDirPath=entityClassFilePath.replace(className, "");
		
		sourceHbmFilePath=entityClassDirPath+"xml/"+sourceHbmName;
		newHbmFilePath=entityClassDirPath+"xml/"+newHbmName;
		
		hbmAbsolutePath=newHbmFilePath.substring(newHbmFilePath.indexOf("classes/")+8);
		
		HbmXMLManageUtil.copyHbmXML(newHbmFilePath	, sourceHbmFilePath, fieldInfoSet,newEntityName);
		HibernateConfigManagerUtil.updateHibernateConfig(configName, hbmAbsolutePath);
		//HibernateSessionFactory.rebuildSessionFactory();
	}
	
	public void updateXML()
		throws FilePathException,FileIsExistsException{
		/*GridTable gt=new GridTable();
		gt.setUniqueCode("10066");
		List list=this.getGridTable(gt);*/
		String gridTableId="10066";
		String entityName="TEMPLATE_TABLE_01";
		String hbmName="TemplateTable01.hbm.xml";
		String newHbmName="TemplateTable02.hbm.xml";
		String newEntityName="TEMPLATE_TABLE_02";
		String configName="hibernate.cfg.xml";
		String componentName="dataProperties";
		
		GridTable gt=this.getGridTable(gridTableId);
		Set<GridColumn> set=gt.getGridColumns();
		
		Set<FieldInfo>  fieldInfoSet=new HashSet<FieldInfo>();
		//初始化fieldInfoSet
		for(GridColumn gc:set){
			FieldInfo fi=new FieldInfo();
			fi.setFieldName(gc.getDataIndex());
			fi.setFieldTypeName(gc.getType());
			fieldInfoSet.add(fi);
		}

		Class clazz=HibernateSessionFactory
				.getClassMapping(entityName)
				.getMappedClass() ;
		String className=HibernateSessionFactory
						.getClassMapping(entityName) 
						.getClassName();
		className = className.substring(className.lastIndexOf(".")+1).concat(".class");
		String filePath=clazz
						.getResource(className).getPath();
		
		filePath=filePath.replace(className, "xml/"+hbmName);
		
		/*ehd.setHem(htm);*/
		
		HibernateMappingManager hmm=new HibernateMappingManager();
		
		
		//创建mapping文件
		CopyFile.copyFile(newHbmName, filePath);
		
		filePath=filePath.replace(hbmName, newHbmName);
		
		
		//修改新的配置文件在hibernate的config的名称
		hmm.updateEntityName(filePath, newEntityName);
		//把新添加爱的model添加到hibernate的config中
		HibernateSessionFactory.getConfiguration().addFile(filePath);
		//修改hibernate 的配置文件
		String filePathClass=filePath.substring(filePath.indexOf("classes/")+8);

		hmm.updateHibernateConfig(configName, newHbmName,filePathClass);
		
		//添加属性
		HibernateEntityManager htm=new HibernateEntityManager(newEntityName,componentName,newHbmName,filePath);
		htm.addEntityField(fieldInfoSet);
		//重新加载hibernate的配置文件
		HibernateSessionFactory.rebuildSessionFactory();
	}
	
	public static void main(String args[]) throws Exception{
		GridTableBusinessImpl tgt=new GridTableBusinessImpl();
		tgt.save();
		/*GridTable gt=tgt.getGridTable("10020");
		System.out.println(gt.getGridColumns().size());
		try {
			BeanInfo bi=Introspector.getBeanInfo(GridTable.class,Object.class);
			PropertyDescriptor[] pds=bi.getPropertyDescriptors();
			for(PropertyDescriptor pd:pds){				
				Object obj=pd.getReadMethod().invoke(gt);
				if((Set.class).isInstance(obj)){
					for(Iterator it=((Set)obj).iterator();it.hasNext();){
						Object o=it.next();
						System.out.println(o.getClass());
					}
				}
				
			}
		} catch (IntrospectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e){
			e.printStackTrace();
		}
		
		JsonHelp<GridTable> jh=new JsonHelp<GridTable>();
		System.out.println(jh.getJson(gt.getGridColumns()));
		Set<GridColumn> set=gt.getGridColumns();
		for(GridColumn gc:set){
			System.out.println(gc.getType());
		}*/
		
		/*PropertyDescriptor pd=new PropertyDescriptor("allowBlank",GridColumn.class);
		System.out.println(pd.getReadMethod());*/
	}
}
